import exam from 'api/exam.js'
import { arrayCopy, swap } from 'utils'

function getValueFromKey(array, k){
	let res = '';
	array.some(ele => {
		let rt = ele.key === k;
		if (rt) res = ele.value;
		return rt;
	}); 
	return res;
};

export default {
	namespaced: true,

	state: {
		courseid: '',
		examType: '',

		end: false,
		problems: [],
		// problems: [{
		// 	"id": 2595,
		// 	"course": 1,
		// 	"type": 1,
		// 	"mark": 1,
		// 	"grade": 3,
		// 	"answer": "A",
		// 	"question": "采用保险人提供的格式条款订立的保险合同中的条款中无效的有()。",
		// 	"sa": "加重投保人、被保险人责任的",
		// 	"sb": "规定等待期的",
		// 	"sc": "强调投保人、被保险人或者受益人依法享有的权利的",
		// 	"sd": "规定免除责任的",
		// 	"se": "",
		// 	"sf": "",
		// 	choice: '',
		// }],
	},
	getters: {
		courseName(state, getters, rootState){
			let courses = rootState.exam.courses;
			return getValueFromKey(courses, state.courseid);
		},
		ExamTypeName(state, getters, rootState) {
			let examTypes = rootState.exam.examTypes;
			return getValueFromKey(examTypes, state.examType);
		},
	},
	mutations: {
		problems({ problems }, newProblems) {
			arrayCopy(problems, newProblems.map(ele => {
				ele.choice = '';
				return ele;
			}));
		},
		start(state, {examType, courseid}){
			state.end = false;
			state.examType = examType;
			state.courseid = courseid;
		},
		end(state){
			state.end = true;
		},
	},
	actions: {
		init({ dispatch }) {},

		startNewExam({ rootState, rootGetters, commit }, {amount=10, courseid=10, examType=1}) {
			let sessionid = rootState.user.sessionid;
			let examTypes = rootState.exam.examTypes;
			let logged = rootGetters['user/logged'];

			for(let ele of examTypes){
				if ('' + examType === '' + ele.key){
					return exam[ele.fn](sessionid, amount, courseid)
								.done(data => {
									commit('start' ,{courseid, examType});
									commit('problems', data);
								});
				}
			}
			return null;
		},
		submit({rootState, rootGetters, state, commit }, score, doneids, rightids, errorids){
			let sessionid = rootState.user.sessionid;
			let courseid = state.courseid;
			let examType = state.examType;
			let examTypes = rootState.exam.examTypes;
			let logged = rootGetters['user/logged'];

			for(let ele of examTypes) {
				if ('' + examType === '' + ele.key){
					return exam[ele.submit](sessionid, courseid, score, doneids, errorids, rightids)
								.done(data => {
									commit('end');
								})
				}
			}
			return null;
		},
	},
}
